package com.tensai.core.mvc.system.controller;

import com.alibaba.fastjson.JSON;
import com.tensai.core.mvc.base.controller.BaseController;
import com.tensai.core.mvc.base.tools.ResultJson;
import com.tensai.core.mvc.base.tools.XTree;
import com.tensai.core.constant.ResponseStatus;
import com.tensai.core.mvc.system.entry.SysGroup;
import com.tensai.core.mvc.system.entry.SysResource;
import com.tensai.core.mvc.system.service.ISysGroupService;
import com.tensai.core.mvc.system.service.ISysResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * 资源路径控制器
 *
 * @author Tensai
 * 2018/12/26
 */
@Controller
@RequestMapping("/system/resource/")
public class SysResourceController extends BaseController<SysResource, Integer, ISysResourceService> {

    @Autowired
    private ISysGroupService sysGroupService;

    /**
     * 保存实体
     *
     * @param sysResource   资源实体
     * @return              操作结果
     */
    @RequestMapping("/save")
    @ResponseBody
    @Override
    public ResultJson save(SysResource sysResource) {
        if (sysResource.getParent() == null) {
            sysResource.setLevel(1);
        } else {
            sysResource.setLevel(sysResource.getParent().getLevel() + 1);
        }
        return getService().save(sysResource);
    }

    @RequestMapping("findByType")
    @ResponseBody
    public ResultJson findByType(String type) {
        return new ResultJson(ResponseStatus.QUERY_SUCCESS, getService().findByType(type));
    }

    /**
     * 获取用户对于资源的权限
     * @param id    用户组id
     * @return      资源权限列表
     */
    @RequestMapping("/getResource")
    @ResponseBody
    public List<XTree> getResource(Integer id){
        SysGroup sysGroup = sysGroupService.findOne(id);
        //JSON的权限判断
        List<Integer> list = JSON.parseArray(sysGroup.getAuthJson(), Integer.class);
        return getService().getUserAuth(list);
    }

    @Override
    protected void initEntity() {
        this.entity = new SysResource();
    }
}

